package com.darren.befriend;

import java.util.ArrayList;
import java.util.Date;

import android.content.Intent;
import android.os.AsyncTask;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;

import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.utilities.MySharedPreferences;
import com.darren.befriend.utilities.Utilities;
import com.darren.befriend.views.MyCustomDialog;
import com.darren.befriend.views.MyProgressDialog;
import com.darren.befriend.views.MyCustomDialog.OnNegativeButtonClick;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

public class SignInActivity extends BaseActivity {

	private EditText mUsernameTxt;
	private EditText mPasswordTxt;
	private MyCustomDialog mErrorDialog;
	private MyProgressDialog mDialog;
	private final String TAG = SignInActivity.class.getSimpleName();

	@Override
	protected int addContent() {

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		return R.layout.layout_sign_in;
	}

	@Override
	protected void initView() {

		mUsernameTxt = (EditText) findViewById(R.id.username_txt);
		mPasswordTxt = (EditText) findViewById(R.id.password_txt);
		Utilities.setFontType(this, mUsernameTxt);
		Utilities.setFontType(this, mPasswordTxt);
		ImageView signInBtn = (ImageView) findViewById(R.id.signin_btn);
		signInBtn.setOnClickListener(this);
		findViewById(R.id.main_view).setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Utilities.hideKeyboard(SignInActivity.this);
				return false;
			}
		});
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		int id = v.getId();
		switch (id) {
		case R.id.signin_btn:
			createDialog();
			mDialog = MyProgressDialog.show(SignInActivity.this, "", "", false,
					false);
			new SignInAsyncTask().execute();
			break;
		default:
			break;
		}
	}

	private class SignInAsyncTask extends AsyncTask<Void, String, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}

		@Override
		protected Void doInBackground(Void... params) {
			logIn();
			return null;
		}

	}

	/**
	 * login
	 */
	private void logIn() {

		if (mUsernameTxt.getText().length() == 0
				|| mPasswordTxt.getText().length() == 0) {
			mErrorDialog.setMessage(getString(R.string.input_length_error));
			mErrorDialog.show();
		} else {
			ParseUser.logInInBackground(mUsernameTxt.getText().toString(),
					mPasswordTxt.getText().toString(), new LogInCallback() {

						@SuppressWarnings("unchecked")
						@Override
						public void done(final ParseUser user, ParseException e) {
							if (user != null) {
								try {
									LogUtil.e(TAG, "user:" + user.getUsername());
									MySharedPreferences.setPreferences(
											MySharedPreferences.PREF_USERNAME,
											user.getUsername());
									MySharedPreferences.setPreferences(
											MySharedPreferences.PREF_PASSWORD,
											mPasswordTxt.getText().toString());
									ArrayList<String> enemyArr = (ArrayList<String>) user
											.get("Enemy");
									if (enemyArr != null) {
										ArrayList<String> newEnemyArr = new ArrayList<String>();
										for (int i = 0; i < enemyArr.size(); i++) {
											String enemy = enemyArr.get(i);
											String[] temp = enemy
													.split("\\$\\$\\$");
											int time = Integer
													.parseInt(temp[1]);
											int currentTime = (int) new Date()
													.getTime() / 1000;
											if ((currentTime - time) > 120) {
												break;
											}
											newEnemyArr.add(enemy);
										}
										user.put("Enemy", newEnemyArr);
									}

									user.put("MeInfo",
											user.getParseObject("MeInfo")
													.fetch());
									user.put("Filter",
											user.getParseObject("Filter")
													.fetch());
									user.put("Status", true);
									user.save();
									if (mGeoPoint != null) {
										user.put("Position", mGeoPoint);
									}

									mParseUser = user;
									mDialog.dismiss();
									Intent homeIntent = new Intent(
											SignInActivity.this,
											HomeActivity.class);
									homeIntent
											.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
													| Intent.FLAG_ACTIVITY_CLEAR_TOP);
									startActivity(homeIntent);
									finish();
								} catch (ParseException e1) {

									mDialog.dismiss();
									mErrorDialog
											.setMessage(getString(R.string.input_incorrect_error));
									mErrorDialog.show();
								}
							} else {
								LogUtil.e(
										TAG,
										"Error: "
												+ getString(R.string.input_incorrect_error));
								mDialog.dismiss();
								mErrorDialog
										.setMessage(getString(R.string.input_incorrect_error));
								mErrorDialog.show();
							}
						}
					});
		}
	}

	/**
	 * create dialog
	 */
	private void createDialog() {
		mErrorDialog = new MyCustomDialog(SignInActivity.this);
		mErrorDialog.setNegativeButton(getString(R.string.ok_label),
				new OnNegativeButtonClick() {

					@Override
					public void onButtonClick(final View view) {
						mErrorDialog.dismiss();
					}
				});
	}
}
